﻿using MaterialDesignThemes.Wpf;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using VIA.Foundation;
using VIA.Integration;
using VIA.Integration.Domain;
using VIA.Integration.Presentation;
using VIA.Integration.Presentation.View;
using VIA.Presentation;

namespace VIA.Project.Presentation.ViewModel.Inspection
{
    internal abstract class OptionViewModel<TView, TOption> : ViewModel<TView>
        where TView : class, IOptionView
        where TOption : class, new()
    {
        protected readonly IServiceProvider _service;
        TOption _option;
        public TOption Option
        {
            get => _option;
            set => SetProperty(ref _option, value);
        }
        Part _station;
        public Part Station
        {
            get => _station;
            set
            {
                if (SetProperty(ref _station, value))
                {
                    Reset();
                }
            }
        }

        public string OptionId => Station?.Id;

        #region Commands

        public IRelayCommand OKCommand { get; }
        public IRelayCommand CancelCommand { get; }
        #endregion

        public OptionViewModel(IServiceProvider service)
        {
            _service = service;
            var commandFactory = service.GetRequiredService<ICommandFactory>();
            OKCommand = commandFactory.Create(OK);
            CancelCommand = commandFactory.Create(Cancel);

        }
        protected virtual async Task OK()
        {
            var v = _service.GetService<IShellService>().ShellWindow as ShellView;
            var b = v.RootDialogHost.CurrentSession;
            try
            {
                var recipe = _service.GetRequiredService<ICurrentRecipe>();
                recipe.Set(OptionId, Option);
                await recipe.SaveAsync();
                ICommand command = DialogHost.CloseDialogCommand;
                command.Execute(true);
            }
            catch (Exception e)
            {
                var messageService = _service.GetService<IMessageService>();
                messageService.ShowError(e, e.Message);
            }
        }
        void Cancel()
        {
            ICommand command = DialogHost.CloseDialogCommand;
            command.Execute(false);
        }
        protected virtual void Reset()
        {
            var recipe = _service.GetRequiredService<ICurrentRecipe>();
            Option = recipe.Get<TOption>(OptionId);
        }
    }
}
